package com.wosiliujing.learning.config;

import com.wosiliujing.learning.handler.FormAuthenticationFailureHandler;
import com.wosiliujing.learning.handler.MobileLoginSuccessHandler;
import com.wosiliujing.learning.mobile.MobileSecurityConfigurer;
import lombok.AllArgsConstructor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.annotation.Order;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.factory.PasswordEncoderFactories;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

/**
 * @author liujing
 * @date 2019/4/27 18:08
 */
@Configuration
@Primary
@Order(90)
@AllArgsConstructor
public class WebSecurityConfigure extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
       http.
               formLogin()
               .loginPage("/token/login")
               .loginProcessingUrl("/token/form")
               //不要加
           //    .successHandler(new FormAuthenticationSuccessHandler())
               .failureHandler(new FormAuthenticationFailureHandler())
               .and().
               authorizeRequests()
               .antMatchers(
                       "/token/**",
                       "/actuator/**",
                       "/mobile/token/**"
               ).permitAll()
               .anyRequest().authenticated()
               .and().csrf().disable()
       .apply(mobileSecurityConfigurer());
    }

    @Override
    public void configure(WebSecurity web) {
        web.ignoring().antMatchers("/css/**");
    }

    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    @Bean
    public AuthenticationSuccessHandler mobileLoginSuccessHandler() {
        return new MobileLoginSuccessHandler();
    }

    @Bean
    public MobileSecurityConfigurer mobileSecurityConfigurer(){
       return  new MobileSecurityConfigurer();
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return PasswordEncoderFactories.createDelegatingPasswordEncoder();
    }
}
